<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>调查问卷管理后台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif;
            background: #f5f5f5;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 12px;
            margin-bottom: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        }

        .header h1 {
            margin-bottom: 10px;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
            margin-right: 10px;
            font-weight: 500;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-danger {
            background: #f44336;
            color: white;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn:hover {
            opacity: 0.9;
        }

        .section {
            background: white;
            padding: 30px;
            border-radius: 12px;
            margin-bottom: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .section h2 {
            color: #333;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #667eea;
        }

        .survey-card {
            background: #f8f9fa;
            padding: 20px;
            margin-bottom: 15px;
            border-radius: 8px;
            border-left: 4px solid #667eea;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .survey-info h3 {
            color: #333;
            margin-bottom: 10px;
        }

        .survey-info p {
            color: #666;
            font-size: 14px;
            margin-bottom: 5px;
        }

        .survey-actions {
            display: flex;
            gap: 10px;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal.show {
            display: flex;
        }

        .modal-content {
            background: white;
            border-radius: 12px;
            padding: 30px;
            max-width: 800px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
        }

        .modal-header {
            margin-bottom: 20px;
        }

        .modal-header h2 {
            color: #333;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 500;
        }

        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }

        .template-selector {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }

        .template-card {
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            padding: 20px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .template-card:hover {
            border-color: #667eea;
            background: #f8f9fa;
        }

        .template-card.selected {
            border-color: #667eea;
            background: #e8eaf6;
        }

        .template-card h3 {
            color: #333;
            margin-bottom: 10px;
        }

        .template-card p {
            color: #666;
            font-size: 14px;
        }

        .editor-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #667eea;
        }

        .editor-section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .editor-section-header h3 {
            color: #333;
        }

        .question-item {
            background: white;
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 6px;
            border: 1px solid #e0e0e0;
        }

        .question-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .question-type-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
            background: #667eea;
            color: white;
        }

        .option-list {
            margin-left: 20px;
            margin-top: 10px;
        }

        .option-item {
            padding: 5px 0;
            color: #666;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }

        .empty-state h3 {
            margin-bottom: 10px;
        }

        .url-display {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 6px;
            border: 1px solid #e0e0e0;
            margin-top: 10px;
        }

        .url-display strong {
            color: #667eea;
            font-size: 16px;
            word-break: break-all;
        }

        .url-display button {
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📊 调查问卷管理系统</h1>
            <p>创建、管理和查看调查问卷</p>
        </div>

        <div class="section">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2 style="margin: 0; padding: 0; border: none;">我的调查问卷</h2>
                <button class="btn btn-primary" onclick="showCreateModal()">+ 创建新调查</button>
            </div>

            <div id="surveysList"></div>
        </div>
    </div>

    <!-- 创建调查模态框 -->
    <div id="createModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>创建新调查</h2>
            </div>

            <div class="form-group">
                <label>选择调查模板</label>
                <div id="templateSelector" class="template-selector"></div>
            </div>

            <div class="form-group">
                <label>调查标题</label>
                <input type="text" id="surveyTitle" placeholder="例如:函数知识掌握情况调查">
            </div>

            <div style="display: flex; gap: 10px; justify-content: flex-end;">
                <button class="btn btn-secondary" onclick="hideCreateModal()">取消</button>
                <button class="btn btn-primary" onclick="createSurvey()">创建并编辑</button>
            </div>
        </div>
    </div>

    <!-- 编辑调查模态框 -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>编辑调查配置</h2>
            </div>

            <div class="form-group">
                <label>调查标题</label>
                <input type="text" id="editSurveyTitle">
            </div>

            <div class="form-group">
                <label>调查说明</label>
                <textarea id="editSurveyDescription" rows="3"></textarea>
            </div>

            <h3 style="margin-top: 30px; margin-bottom: 15px;">调查内容</h3>
            <div id="sectionsEditor"></div>

            <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 30px;">
                <button class="btn btn-secondary" onclick="hideEditModal()">取消</button>
                <button class="btn btn-success" onclick="saveSurveyConfig()">保存配置</button>
            </div>
        </div>
    </div>

    <script>
        let templates = [];
        let currentSurveyId = null;
        let currentConfig = null;
        let selectedTemplate = null;

        // 页面加载时执行
        window.onload = function() {
            loadTemplates();
            loadSurveys();
        };

        // 加载模板列表
        function loadTemplates() {
            fetch('/api/templates')
                .then(r => r.json())
                .then(data => {
                    templates = data;
                })
                .catch(err => console.error('加载模板失败:', err));
        }

        // 加载调查列表
        function loadSurveys() {
            fetch('/api/surveys')
                .then(r => r.json())
                .then(surveys => {
                    const container = document.getElementById('surveysList');

                    if (surveys.length === 0) {
                        container.innerHTML = `
                            <div class="empty-state">
                                <h3>还没有创建任何调查</h3>
                                <p>点击上方"创建新调查"按钮开始</p>
                            </div>
                        `;
                        return;
                    }

                    let html = '';
                    surveys.forEach(survey => {
                        const date = new Date(survey.createdAt).toLocaleString('zh-CN');
                        html += `
                            <div class="survey-card">
                                <div class="survey-info">
                                    <h3>${survey.title}</h3>
                                    <p>📅 创建时间: ${date}</p>
                                    <p>📊 提交数量: ${survey.submissionCount} 份</p>
                                    <p>🔗 学生访问: <code>/student/${survey.surveyId}</code></p>
                                </div>
                                <div class="survey-actions">
                                    <button class="btn btn-primary" onclick="viewStats('${survey.surveyId}')">查看统计</button>
                                    <button class="btn btn-success" onclick="editSurvey('${survey.surveyId}')">编辑</button>
                                    <button class="btn btn-secondary" onclick="copyLink('${survey.surveyId}')">复制链接</button>
                                    <button class="btn btn-danger" onclick="deleteSurvey('${survey.surveyId}', '${survey.title}')">删除</button>
                                </div>
                            </div>
                        `;
                    });

                    container.innerHTML = html;
                })
                .catch(err => {
                    console.error('加载调查列表失败:', err);
                    document.getElementById('surveysList').innerHTML = `
                        <div class="empty-state">
                            <h3>加载失败</h3>
                            <p>请确保服务器正在运行</p>
                        </div>
                    `;
                });
        }

        // 显示创建调查模态框
        function showCreateModal() {
            // 渲染模板选择器
            const selector = document.getElementById('templateSelector');
            let html = '';

            templates.forEach(template => {
                html += `
                    <div class="template-card" onclick="selectTemplate('${template.templateId}')">
                        <h3>${template.templateName}</h3>
                        <p>${template.description || '无描述'}</p>
                    </div>
                `;
            });

            selector.innerHTML = html;
            document.getElementById('createModal').classList.add('show');
        }

        function hideCreateModal() {
            document.getElementById('createModal').classList.remove('show');
            selectedTemplate = null;
        }

        function selectTemplate(templateId) {
            selectedTemplate = templateId;

            // 高亮选中的模板
            const cards = document.querySelectorAll('.template-card');
            cards.forEach(card => card.classList.remove('selected'));
            event.target.closest('.template-card').classList.add('selected');

            // 自动填入默认标题
            const template = templates.find(t => t.templateId === templateId);
            if (template) {
                // 从模板获取标题需要额外请求,这里简化处理
                document.getElementById('surveyTitle').value = template.templateName;
            }
        }

        // 创建调查
        function createSurvey() {
            if (!selectedTemplate) {
                alert('请选择一个模板');
                return;
            }

            const title = document.getElementById('surveyTitle').value.trim();
            if (!title) {
                alert('请输入调查标题');
                return;
            }

            fetch('/api/survey/create', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    templateId: selectedTemplate,
                    title: title
                })
            })
            .then(r => r.json())
            .then(result => {
                if (result.success) {
                    alert('✅ 创建成功!');
                    hideCreateModal();
                    loadSurveys();

                    // 自动打开编辑器
                    setTimeout(() => editSurvey(result.surveyId), 300);
                } else {
                    alert('❌ 创建失败: ' + result.message);
                }
            })
            .catch(err => {
                alert('❌ 创建失败: ' + err.message);
            });
        }

        // 编辑调查
        function editSurvey(surveyId) {
            currentSurveyId = surveyId;

            fetch(`/api/survey/${surveyId}/config`)
                .then(r => r.json())
                .then(config => {
                    currentConfig = config;

                    // 填入基本信息
                    document.getElementById('editSurveyTitle').value = config.title;
                    document.getElementById('editSurveyDescription').value = config.description || '';

                    // 渲染各部分
                    renderSectionsEditor(config.sections);

                    document.getElementById('editModal').classList.add('show');
                })
                .catch(err => {
                    alert('加载配置失败: ' + err.message);
                });
        }

        function hideEditModal() {
            document.getElementById('editModal').classList.remove('show');
            currentSurveyId = null;
            currentConfig = null;
        }

        // 渲染编辑器
        function renderSectionsEditor(sections) {
            const container = document.getElementById('sectionsEditor');
            let html = '';

            sections.forEach((section, sIndex) => {
                html += `
                    <div class="editor-section">
                        <div class="editor-section-header">
                            <h3>${section.title}</h3>
                            <div>
                                <button class="btn btn-secondary" onclick="editSection(${sIndex})">编辑</button>
                                <button class="btn btn-danger" onclick="deleteSection(${sIndex})">删除</button>
                            </div>
                        </div>
                `;

                section.questions.forEach((q, qIndex) => {
                    html += `
                        <div class="question-item">
                            <div class="question-header">
                                <div>
                                    <span class="question-type-badge">${getTypeName(q.type)}</span>
                                    <strong>${q.question}</strong>
                                    ${q.required ? '<span style="color: red;">*</span>' : ''}
                                </div>
                                <div>
                                    <button class="btn btn-secondary" style="padding: 6px 12px; font-size: 12px;" onclick="editQuestion(${sIndex}, ${qIndex})">编辑</button>
                                    <button class="btn btn-danger" style="padding: 6px 12px; font-size: 12px;" onclick="deleteQuestion(${sIndex}, ${qIndex})">删除</button>
                                </div>
                            </div>
                    `;

                    if (q.options) {
                        html += '<div class="option-list">';
                        q.options.forEach(opt => {
                            html += `<div class="option-item">• ${opt}</div>`;
                        });
                        html += '</div>';
                    }

                    if (q.rows && q.columns) {
                        html += `<div class="option-list">`;
                        html += `<div class="option-item">行: ${q.rows.join(', ')}</div>`;
                        html += `<div class="option-item">列: ${q.columns.join(', ')}</div>`;
                        html += `</div>`;
                    }

                    html += '</div>';
                });

                html += `
                        <button class="btn btn-primary" style="margin-top: 10px;" onclick="addQuestion(${sIndex})">+ 添加问题</button>
                    </div>
                `;
            });

            html += '<button class="btn btn-primary" onclick="addSection()">+ 添加新部分</button>';

            container.innerHTML = html;
        }

        function getTypeName(type) {
            const names = {
                'text': '文本',
                'textarea': '长文本',
                'radio': '单选',
                'checkbox': '多选',
                'table': '表格',
                'code_display': '代码',
                'text_display': '说明'
            };
            return names[type] || type;
        }

        // 简化版的编辑功能(弹窗输入)
        function editSection(sIndex) {
            const newTitle = prompt('修改部分标题:', currentConfig.sections[sIndex].title);
            if (newTitle) {
                currentConfig.sections[sIndex].title = newTitle;
                renderSectionsEditor(currentConfig.sections);
            }
        }

        function deleteSection(sIndex) {
            if (confirm('确定删除这个部分吗?')) {
                currentConfig.sections.splice(sIndex, 1);
                renderSectionsEditor(currentConfig.sections);
            }
        }

        function addSection() {
            const title = prompt('输入新部分的标题:');
            if (title) {
                currentConfig.sections.push({
                    sectionId: 'section_' + Date.now(),
                    title: title,
                    questions: []
                });
                renderSectionsEditor(currentConfig.sections);
            }
        }

        function editQuestion(sIndex, qIndex) {
            const question = currentConfig.sections[sIndex].questions[qIndex];
            const newText = prompt('修改问题文本:', question.question);
            if (newText) {
                question.question = newText;
                renderSectionsEditor(currentConfig.sections);
            }
        }

        function deleteQuestion(sIndex, qIndex) {
            if (confirm('确定删除这个问题吗?')) {
                currentConfig.sections[sIndex].questions.splice(qIndex, 1);
                renderSectionsEditor(currentConfig.sections);
            }
        }

        function addQuestion(sIndex) {
            const text = prompt('输入问题文本:');
            if (!text) return;

            const type = prompt('选择题型:\n1=文本 2=长文本 3=单选 4=多选', '1');
            const typeMap = {'1': 'text', '2': 'textarea', '3': 'radio', '4': 'checkbox'};
            const questionType = typeMap[type] || 'text';

            const newQuestion = {
                id: 'q_' + Date.now(),
                type: questionType,
                question: text,
                required: false
            };

            if (questionType === 'radio' || questionType === 'checkbox') {
                const opts = prompt('输入选项(用逗号分隔):');
                newQuestion.options = opts ? opts.split(',').map(s => s.trim()) : [];
            }

            currentConfig.sections[sIndex].questions.push(newQuestion);
            renderSectionsEditor(currentConfig.sections);
        }

        // 保存配置
        function saveSurveyConfig() {
            currentConfig.title = document.getElementById('editSurveyTitle').value;
            currentConfig.description = document.getElementById('editSurveyDescription').value;

            fetch(`/api/survey/${currentSurveyId}/config`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(currentConfig)
            })
            .then(r => r.json())
            .then(result => {
                if (result.success) {
                    alert('✅ 保存成功!');
                    hideEditModal();
                    loadSurveys();
                } else {
                    alert('❌ 保存失败: ' + result.message);
                }
            })
            .catch(err => {
                alert('❌ 保存失败: ' + err.message);
            });
        }

        // 查看统计
        function viewStats(surveyId) {
            window.open(`/teacher/${surveyId}`, '_blank');
        }

        // 复制链接
        function copyLink(surveyId) {
            const link = `${window.location.protocol}//${window.location.host}/student/${surveyId}`;
            navigator.clipboard.writeText(link).then(() => {
                alert('✅ 学生访问链接已复制到剪贴板:\n' + link);
            }).catch(() => {
                prompt('复制以下链接:', link);
            });
        }

        // 删除调查
        function deleteSurvey(surveyId, title) {
            if (!confirm(`确定要删除"${title}"吗?\n此操作将同时删除所有收集的数据,且不可恢复!`)) {
                return;
            }

            fetch(`/api/survey/${surveyId}/delete`, {
                method: 'POST'
            })
            .then(r => r.json())
            .then(result => {
                if (result.success) {
                    alert('✅ 删除成功');
                    loadSurveys();
                } else {
                    alert('❌ 删除失败: ' + result.message);
                }
            })
            .catch(err => {
                alert('❌ 删除失败: ' + err.message);
            });
        }
    </script>
</body>
</html>
